package com.example.newheze.FieldMessage;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.newheze.MainActivity;
import com.example.newheze.R;
import com.example.newheze.vo.Data;
import com.example.newheze.vo.Dtu;
import com.example.newheze.vo.JsonData;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import lecho.lib.hellocharts.view.LineChartView;
import okhttp3.*;

public class MessageActivity extends Fragment implements ViewPager.OnPageChangeListener,View.OnClickListener{
    private LineChartView[] lineChartViews;
    private MyLineChartData[] myLineChartDatas;
    private MyViewPager viewPager;
    private List<View> views;
//    private TextView textView;
//    private TextView textView1;
//    private TextView textView2;
//    private TextView textView3;
    private Button button;
    private int[] chooseImage={R.drawable.choose1,R.drawable.choose2,R.drawable.choose3,R.drawable.choose4};
    private int[] unchooseImage={R.drawable.unchoose1,R.drawable.unchoose2,R.drawable.unchoose3,R.drawable.unchoose4};
    private ImageView[] chooses;
    private ViewPagerAdapter adapter;
    private LinearLayout linearLayout;
    private int cuurentPage;
    private AnalogData analogData=new AnalogData();
    private LineChartViewAdapter[] lineChartViewAdapters;
    private Handler handler;
    private TextView soilhumi1;
    private TextView soilhumi2;
    private TextView airtemp;
    private TextView airhumi;
    private TextView sundata;
    private TextView coo;
    private Data data=new Data();
    private Dtu dtu=new Dtu();

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_fieldmessage, container, false);
        //初始化view
        linearLayout=view.findViewById(R.id.choose_state);
        soilhumi1 = view.findViewById(R.id.soilhumi1);
        soilhumi2 = view.findViewById(R.id.soilhumi2);
        airtemp = view.findViewById(R.id.airtemp);
        airhumi = view.findViewById(R.id.airhumi);
        sundata = view.findViewById(R.id.sundata);
        coo = view.findViewById(R.id.coo);
        viewPager=new MyViewPager(this.getActivity());
        viewPager=view.findViewById(R.id.viewpager);
        views=new ArrayList<View>();
        adapter=new ViewPagerAdapter(views);
        getData();
//        Bundle bundle = this.getArguments();
//        if(bundle.getString("coo") != null) {
//            Log.i("soilhumi1",bundle.getString("soilhumi1"));
//            soilhumi1.setText(bundle.getString("soilhumi1"));
//            soilhumi2.setText(bundle.getString("soilhumi2"));
//            airtemp.setText(bundle.getString("airtemp"));
//            airhumi.setText(bundle.getString("airhumi"));
//            sundata.setText(bundle.getString("sundata"));
//            coo.setText(bundle.getString("coo"));
//        }

        //初始化折线图
        myLineChartDatas=new MyLineChartData[4];
        lineChartViews=new LineChartView[4];
        lineChartViewAdapters=new LineChartViewAdapter[4];

        for(int i=0;i<4;i++){
            myLineChartDatas[i]=new MyLineChartData();

        }
        /*
         在这里添加传输过来的数据，不要用AnalogData类，应创建并使用
         HistoryData类实例，并将下列的方法替换。
        示例：
        HistoryData historyData[]=new HistoryData[4];
        historyData[0].setAirHumidity();
        historyData[0].setHistoryDate();
        myLineChartDatas[0].setX(historyData[0].getAirHumidity());
        myLineChartDatas[0].setY(analogData[0].gethistoryDate());
         */
        myLineChartDatas[0].setX(analogData.getDate1());
        myLineChartDatas[0].setY(analogData.getInfo1());
        myLineChartDatas[1].setX(analogData.getDate2());
        myLineChartDatas[1].setY(analogData.getInfo2());
        myLineChartDatas[2].setX(analogData.getDate3());
        myLineChartDatas[2].setY(analogData.getInfo3());
        myLineChartDatas[3].setX(analogData.getDate4());
        myLineChartDatas[3].setY(analogData.getInfo4());
        for(int i=0;i<4;i++){
            lineChartViews[i]=view.findViewById(R.id.chart);
        }
        initData();
        return view;
    }

//    private void initCurrentData() {      //显示当前数据
//        textView = view.findViewById(R.id.air_humidity);
//        textView1 = view.findViewById(R.id.air_temperature);
//        textView2 = view.findViewById(R.id.soid_humidity1);
//        textView3 = view.findViewById(R.id.soid_humidity2);
//        CurrentData currentData = new CurrentData();
//        //currentData.setAirHumidity("");
//        //.......
//        //textView.setText(currentData.getAirHumidity());
//        //.......
//    }
    private void initData(){    //为折线图添加数据
        ViewGroup.LayoutParams layoutParams=new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        for(int i=0;i<4;i++){
            lineChartViews[i]=new LineChartView(this.getActivity());
            lineChartViewAdapters[i]=new LineChartViewAdapter(lineChartViews[i],myLineChartDatas[i]);
            lineChartViewAdapters[i].getAxisXLables();
            lineChartViewAdapters[i].getAxisPoints();
            lineChartViewAdapters[i].initLineChart();
            lineChartViews[i].setLayoutParams(layoutParams);
            views.add(lineChartViews[i]);
        }
        initChoose();

        viewPager.setAdapter(adapter);
        viewPager.setOnPageChangeListener(this);
    }
    private void initChoose(){       //初始化选项栏
        chooses=new ImageView[4];
        for(int i=0;i<linearLayout.getChildCount();i++){
            chooses[i]=(ImageView) linearLayout.getChildAt(i);
            chooses[i].setImageResource(unchooseImage[i]);
            chooses[i].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int i=(Integer) view.getTag();
                    viewPager.setCurrentItem(i);
                }
            });
            chooses[i].setTag(i);
            cuurentPage=0;
            chooses[cuurentPage].setImageResource(R.drawable.choose1);
        }
    }

    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    public void onPageSelected(int position) {
        setCurrentPoint(position);
    }
    private void setCurrentPoint(int position){     //为viewpager选项设置点击事件
        for(int i=0;i<linearLayout.getChildCount();i++){
            chooses[i]=(ImageView) linearLayout.getChildAt(i);
            chooses[i].setImageResource(unchooseImage[i]);
        }
        chooses[position].setImageResource(chooseImage[position]);
    }
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onClick(View view) {
        //initCurrentData();
    }
    public void getData(){
        String address="http://123.207.166.108:8083/green/getdata";
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("limit",10);
            jsonObject.put("currentPage",1);
            jsonObject.put("hoursetype","022");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        sendRequestWithOkHttp(address, jsonObject);
    }
    private void sendRequestWithOkHttp(final String address,  final JSONObject jsonObject){
        new Thread(new Runnable() {
            @Override
            public void run() {
                MediaType JSONObject = MediaType.parse("application/json; charset=utf-8");
                RequestBody requestBody = RequestBody.create(JSONObject, jsonObject.toString());
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url(address).post(requestBody).build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(okhttp3.Call call, IOException e) {
                        setResult(e.getMessage(),false);
                        Log.i("cuowu",e.getMessage());
                    }

                    @Override
                    public void onResponse(okhttp3.Call call, Response response) throws IOException {
                        String responseData = response.body().string();
                        setResult(responseData,true);
                        Log.i("message",responseData.toString());
                    }
                });

            }
        }).start();
    }

    private void setResult(final String msg,final boolean success){
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(success){
                    try {
                        FragmentManager fragmentManager = getFragmentManager();
                        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                        JSONObject jsonObject = new JSONObject(msg);
                        JsonData jsonData = new JsonData(jsonObject.getString("msg"),new JSONArray(jsonObject.getString("rows")),jsonObject.getString("success"),jsonObject.getString("total"));
                        JSONArray jsonArray = jsonData.getRows();
                        JSONObject jsonObject1 =jsonArray.getJSONObject(0);
                        Log.i("soilhumi1",jsonObject1.getString("soilhumi1"));
                        data = new Data(jsonObject1.getString("soilhumi1"),jsonObject1.getString("soilhumi2"),jsonObject1.getString("airtemp"),jsonObject1.getString("airhumi"),jsonObject1.getString("sundata"),jsonObject1.getString("coo"));
                        if(data.getSoilhumi1() == "null")
                            data.setSoilhumi1("0");
                        if(data.getSoilhumi2()=="null")
                            data.setSoilhumi2("0");
                        if(data.getAirhumi()=="null")
                            data.setAirhumi("0");
                        if(data.getAirtemp()=="null")
                            data.setAirtemp("0");
                        if(data.getSundata()=="null")
                            data.setSundata("0");
                        if(data.getCoo()=="null")
                            data.setCoo("0");

                        soilhumi1.setText(data.getSoilhumi1());
                        soilhumi2.setText(data.getSoilhumi2());
                        airtemp.setText(data.getAirtemp());
                        airhumi.setText(data.getAirhumi());
                        sundata.setText(data.getSundata());
                        coo.setText(data.getCoo());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                else{
                    Toast.makeText(getActivity(), "请求失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void sendMessage(){
        String command = null;
        if(dtu.getDtu().equals("031"))
            command = "BB00dongping001EF";
        else command = "BB00dongping002EF";
        new Thread(new Sendcommand(handler, command)).start();
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        getData();
    }
}
